<%--
  Created by IntelliJ IDEA.
  User: Markrui
  Date: 2016/3/12
  Time: 21:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="header.jsp" %>
<div id="page-wrapper">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">用户管理</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <div class="col-sm-12" >
            <button type="button" data-toggle="modal" class="btn btn-primary" data-target="#user_modal" data-backdrop="static">添加用户</button>
            <br><br>
        </div>
        <div class="col-sm-12">
            <br>
            <table id="user_table" class="table table-hover table-bordered table-striped table-striped">
                <thead>
                <tr>
                    <td>序号</td>
                    <td>用户名</td>
                    <td>用户角色</td>
                    <td>上次登录</td>
                    <td>操作</td>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <!-- /.row -->
</div>

<%--modal--%>
<div id="user_modal" class="modal fade">
    <div class="modal-dialog" >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">添加用户</h4>
            </div>
            <div class="modal-body">
                <div class="row">

                    <div class="form-group">
                        <form id="user_form" action='' method="post">
                            <div class="col-sm-12">
                                <div class="col-sm-1"></div>
                                <div class="col-sm-3" style="padding-top:5px">
                                    <label for="groupId" class="control-label">选定角色：</label>
                                </div>
                                <div class="col-sm-6">
                                    <select class="groupId form-control" id="groupId" name="groupId" multiple="multiple">

                                    </select>
                                </div>
                            </div>
                            <div class="col-sm-12">
                                <br>
                                <div class="col-sm-1"></div>
                                <div class="col-sm-3" style="padding-top:5px">
                                    <label for="username" class="control-label">用户名：</label>
                                </div>
                                <div class="col-sm-6">
                                    <input id="username" name="username" placeholder="请输入用户名" class="form-control" />
                                </div>
                            </div>
                            <div class="col-sm-12">
                                <br>
                                <div class="col-sm-1"></div>
                                <div class="col-sm-3" style="padding-top:5px">
                                    <label for="password" class="control-label">密码：</label>
                                </div>
                                <div class="col-sm-6">
                                    <input id="password" name="password" type="password" placeholder="请输入密码" class="form-control" />
                                </div>
                            </div>
                            <div class="col-sm-12">
                                <br>
                                <div class="col-sm-1"></div>
                                <div class="col-sm-3" style="padding-top:5px">
                                    <label for="idCard" class="control-label">身份证：</label>
                                </div>
                                <div class="col-sm-6">
                                    <input id="idCard" name="idCard" placeholder="请输入身份证号码" class="form-control" />
                                </div>
                            </div>
                            <%--<div class="col-sm-12">--%>
                                <%--<br>--%>
                                <%--<div class="col-sm-1"></div>--%>
                                <%--<div class="col-sm-3" style="padding-top:5px">--%>
                                    <%--<label for="password1" class="control-label">密码：</label>--%>
                                <%--</div>--%>
                                <%--<div class="col-sm-6">--%>
                                    <%--<input id="password1" name="password1" type="password1" placeholder="请确认密码" class="form-control" />--%>
                                <%--</div>--%>
                            <%--</div>--%>
                            <%--<div class="col-sm-12">--%>
                                <%--<br>--%>
                                <%--<div class="col-sm-1"></div>--%>
                                <%--<div class="col-sm-3" style="padding-top:5px">--%>
                                    <%--<label for="group" class="control-label">用户组：</label>--%>
                                <%--</div>--%>
                                <%--<div class="col-sm-6">--%>
                                    <%--<select class="form-control" id="group" name="group">--%>
                                        <%--<option value="0">内部用户</option>--%>
                                        <%--<option value="1">外部用户</option>--%>
                                    <%--</select>--%>
                                <%--</div>--%>
                            <%--</div>--%>
                        </form>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" onclick="submit()">提交</button>
                <button class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<!-- /#page-wrapper -->
<%@include file="footer.jsp" %>
<link rel="stylesheet" href="../../bower_components/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" type="text/css"/>
<script src="../../bower_components/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<script>
    $(document).ready(function() {
        loadOption();
        loadTable();
    });

    var userId = "";
    $('#user_modal').on("hidden.bs.modal",function(e){
        userId = "";
        $('#groupId').multiselect('deselect', $('#groupId').val());
        $("#username").attr('disabled', false);
        $("#username").val('');
        $("#idCard").val('');
    });

    var table;
    function loadTable(){
        $.ajax({
            url: rootUrl+'mng/user',
            type: 'get',
            dataType: 'json'
        })
        .success(function(data){
            console.log("data:",data);

            table = $('#user_table').DataTable({
                "bProcessing": true,
                "bDestroy": true,
                "sPaginationType" : "full_numbers",
                "oLanguage" : {
                    "sLengthMenu": "每页显示 _MENU_ 条记录",
                    "sZeroRecords": "抱歉， 没有找到",
                    "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                    "sInfoEmpty": "没有数据",
                    "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                    "sZeroRecords": "没有检索到数据",
                    "sSearch": "搜索: &nbsp",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": "前一页",
                        "sNext": "后一页",
                        "sLast": "尾页"
                    }
                },
                "data":data.data.users,
                "columns": [
                    { "data": 'userId' },
                    { "data": 'username' },
                    { "data": 'groupEntities'},
                    { "data": 'lastVisitTime' },
                    { "data": 'userId' }
                ],
                "columnDefs": [
                    {
                        "targets": 0,
                        "render": function (data, type, row, table) {
                            return table.row + 1;
                        }
                    },
                    {
                        "targets": 2,
                        "render": function (data, type, row, table) {
                            //console.log(data);
                            var name = "";
                            if(data != null && data.length > 0 ){
                                for(var i = 0; i < data.length; i++){
                                    name += data[i].name + " ";
                                }
                            }else{
                                name+="暂无角色"
                            }

                            return name;
                        }
                    },
                    {
                        "targets": 4,
                        "render": function (data, type, row, table) {
                            return '<button class="btn btn-primary" onclick="openModal(\''+data+'\')">修改信息</button> '+
                                    '<button class="btn btn-primary" onclick="setAdmin(\''+data+'\',1)">设置管理员</button>';
                        }
                    }]
            });
        });
    }

    function loadOption(){
        var multiselectSetting = {
            buttonWidth: '100%',
            enableFiltering: true,
            filterPlaceholder: '搜索',
            buttonText: function(options) {
                if (options.length == 0) {
                    return '没有选择角色 ';
                }
                else if (options.length > 6) {
                    return '已选择' + options.length + ' 个角色  ';
                }
                else {
                    var selected = '';
                    options.each(function() {
                        selected += $(this).text() + ', ';
                    });
                    return selected.substr(0, selected.length -2) + ' ';
                }
            }
        };
        $.ajax({
            url: rootUrl+'mng/group',
            type: 'get',
            dataType: 'json'
        })
        .success(function(data){
            var groups = data.data.groups;
            var html = "";
            for(var i = 0; i < groups.length; i++){
                html += '<option value="'+groups[i].groupId+'">'+groups[i].name+'</option>';
            }
            $("#groupId").html(html);
            $('#groupId').multiselect(multiselectSetting);
        });
    }

    // 点击修改信息
    function openModal(id){
        userId = id;
        $.ajax({
            url: rootUrl+'mng/user/'+id,
            type: 'get',
            dataType: 'json'
        })
        .success(function(data){
            $("#username").val(data.username);
            $("#password").val(data.password);
            $("#username").attr('disabled', true);
            $("#idCard").val(data.idCard);
            var groupId = [];
            for (var i = 0; i < data.groupEntities.length; i++) {
                groupId.push(data.groupEntities[i].groupId);
            }
            $('#groupId').multiselect('select', groupId);
            $('#user_modal').modal({
                backdrop : "static"
            });

//            if(groupId.length > 0){
//                for(var index = 0; index < groupId.length;index++)
//                {
//                    console.log("item:",groupId[index]);
//                    $("#groupId option").each(function(){
//                        console.log("this :",$(this));
//                        if(groupId[index] == $(this).val()){
//
//                            $(this).selected=true;
//                        }
//                    });
//                }
//            }

        });
    }

    function setAdmin(id,adminCode){
        $.ajax({
            url: rootUrl+'mng/user/'+id+'/admin/'+adminCode,
            type: 'put',
            dataType: 'json'
        })
        .success(function(data){
            location.reload();
        });
    }
    function submit(){
        var userEntity ={
            username:$("#username").val(),
            password:$.md5($("#password").val()),
            idCard:$("#idCard").val(),
            groupEntities:[
            ]
        };

        $("#groupId option:selected").each(function(){
            var groupEntity={};
            groupEntity.groupId = $(this).val();
            groupEntity.name = $(this).text();
            userEntity.groupEntities.push(groupEntity);
        });

        console.log("提交的userEntity:",userEntity);

        console.log($('#user_form').serialize());
        if(userId == ""){

            $.ajax({
                url: rootUrl+'mng/user/',
                contentType:"application/json",
                type: 'post',
                dataType:'JSON',
                data:JSON.stringify(userEntity)
            }).success(function(data){
                $('#user_modal').modal('hide');
                location.reload();
             });
//            $('#user_form').ajaxSubmit({
//                url:rootUrl+"mng/user/",
//                type:"post",
//                success:function(data){
//                    $('#user_modal').modal('hide');
//                    //location.reload();
//                }
//            });
        }else{
//            userEntity.userId = userId;

            $.ajax({
                url:rootUrl+"mng/user/"+userId,
                contentType:"application/json",
                type:"put",
                dataType:'JSON',
                data:JSON.stringify(userEntity)
            }).success(function(data){
                $('#user_modal').modal('hide');
                location.reload();
            });

//            $('#user_form').ajaxSubmit({
//                url:rootUrl+"mng/user/"+userId,
//                type:"put",
//                success:function(data){
//                    $('#user_modal').modal('hide');
//                    location.reload();
//                }
//            });
        }

    }
</script>